package text.editor;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextEditor {
    public static void main(String[] args) {
        TextEditor editor = new TextEditor();
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Please enter the text:");
        String text = scanner.nextLine();
        
        System.out.println("Validating text: " + text);
        
        if (editor.validateText(text)) 
        {
            System.out.println("Text is valid.");
            Map<Character, Integer> charCount = editor.countCharacters(text);
            System.out.println("Character counts: " + charCount);
        }
        else
        {
            System.out.println("Text does not match the required format.");
        }
        
        scanner.close();
    }

    
    public boolean validateText(String text) {
        String regex = "^[a-zA-Z0-9,\\s!]+$"; 
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        return matcher.matches();
    }

    
    public <T extends CharSequence> Map<Character, Integer> countCharacters(T text) 
    {
        Map<Character, Integer> charCountMap = new HashMap<>();
        for (int i = 0; i < text.length(); i++) 
        {
            char c = text.charAt(i);
            charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
        }
        return charCountMap;
    }

    
    class TextExceptionHandler 
    {
        public void logException(Exception e) 
        {
            System.err.println("An error occurred: " + e.getMessage());
        }
    }
}
